package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.tool.Message;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 审批Controller
 * 
 * @author ruoyi
 * @date 2020-12-13
 */
@Controller
@RequestMapping("/system/approve")
public class SysApproveController extends BaseController
{
    private String prefix = "system/approve";

    @Autowired
    private ISysApproveService sysApproveService;
    @Autowired
    private ISysProcurementdeclareService sysProcurementdeclareService;
    @Autowired
    private ISysDeclaregoodsService sysDeclaregoodsService;
    @Autowired
    private ISysOfferinfoService sysOfferinfoService;
    @Autowired
    private ISysSupplierService sysSupplierService;
    @Autowired
    private ISysGoodparameterService sysGoodparameterService;
    @Autowired
    private RuoYiConfig ruoYiConfig;

    @RequiresPermissions("system:approve:view")
    @GetMapping("/approve1")
    public String approve()
    {
        return prefix + "/approve";
    }
    @RequiresPermissions("system:approve:view")
    @GetMapping("/approve2")
    public String approve2()
    {
        return prefix + "/approve2";
    }
    /**
     * 查询未审批列表
     */
    @RequiresPermissions("system:approve:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysApprove sysApprove)
    {
        startPage();
        List<SysApprove> list = sysApproveService.selectSysApproveList(sysApprove);
        return getDataTable(list);
    }
    /**
     * 查询未审批列表
     */
    @RequiresPermissions("system:approve:list")
    @PostMapping("/list2")
    @ResponseBody
    public TableDataInfo list2(SysApprove sysApprove)
    {
        startPage();
        List<SysApprove> list = sysApproveService.selectSysApproveList2(sysApprove);
        return getDataTable(list);
    }
    /**
     * 导出审批列表
     */
    @RequiresPermissions("system:approve:export")
    @Log(title = "审批", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysApprove sysApprove)
    {
        List<SysApprove> list = sysApproveService.selectSysApproveList(sysApprove);
        ExcelUtil<SysApprove> util = new ExcelUtil<SysApprove>(SysApprove.class);
        return util.exportExcel(list, "approve");
    }

    /**
     * 新增审批
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存审批
     */
    @RequiresPermissions("system:approve:add")
    @Log(title = "审批", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SysApprove sysApprove)
    {
        SysUser sysUser = ShiroUtils.getSysUser();
        String unitName = sysUser.getUserName();
        SysProcurementdeclare sysProcurementdeclare = sysProcurementdeclareService.selectSysProcurementdeclareById(sysApprove.getProcurementDeclareId());
        sysApprove.setAttribute2(sysProcurementdeclare.getProjectNumber());//项目编号
        sysApprove.setAttribute3(unitName);//采购单位名称
        /**
         * 主管单位审批结果 approve.setApprovalResult(1);
         * //业务科室审批结果
         * approve.setyApproveResult();
         * //采购办审批结果
         * approve.setCgbApproveResult();
         */

        sysApprove.setCgbApproveResult(0);
        return toAjax(sysApproveService.insertSysApprove(sysApprove));
    }

    /**
     * 修改审批
     */
    @GetMapping("/edit/{approveId}")
    public String edit(@PathVariable("approveId") Long approveId, ModelMap mmap)
    {
        SysApprove sysApprove = sysApproveService.selectSysApproveById(approveId);
        mmap.put("sysApprove", sysApprove);
        return prefix + "/edit";
    }

    /**
     * 修改保存审批
     */
    @RequiresPermissions("system:approve:edit")
    @Log(title = "审批", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysApprove sysApprove)
    {
        String cgbTime = DateUtils.getTime();
        sysApprove.setCgbApproveTime(cgbTime);
        return toAjax(sysApproveService.updateSysApprove(sysApprove));
    }

    /**
     * 删除审批
     */
    @RequiresPermissions("system:approve:remove")
    @Log(title = "审批", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(sysApproveService.deleteSysApproveByIds(ids));
    }

    /**
     *采购申报作废
     * @param approveId
     * @param mmap
     * @return
     */

    @GetMapping("/zuofei/{approveId}")
    public String zuofei(@PathVariable("approveId")Long approveId, ModelMap mmap){
        SysApprove sysApprove = sysApproveService.selectSysApproveById(approveId);
        mmap.put("sysApprove",sysApprove);
        return prefix + "/zuofei";
    }

    /**
     * 采购审批预览
     * @param procurementDeclareId
     * @param mmap
     * @return
     */
    @GetMapping("/yulan/{procurementDeclareId}")
    public String yulan(@PathVariable("procurementDeclareId")Long procurementDeclareId, ModelMap mmap){
        SysProcurementdeclare sysProcurementdeclare = sysProcurementdeclareService.selectSysProcurementdeclareById(procurementDeclareId);
        sysProcurementdeclare.setCreateTime(sysProcurementdeclare.getCreateTime());
        SysDeclaregoods sysDeclaregoods = new SysDeclaregoods();
        sysDeclaregoods.setProcurementDeclareId(procurementDeclareId);
        List<SysDeclaregoods> sysDeclaregoodsList = sysDeclaregoodsService.selectSysDeclaregoodsList(sysDeclaregoods);
        Double sumPrice = 0.00;
        if(sysDeclaregoodsList.size()>0){
            sysProcurementdeclare.setDeclareGoods(sysDeclaregoodsList);
            for (int i = 0;i<sysDeclaregoodsList.size();i++){
                sumPrice+=sysDeclaregoodsList.get(i).getSumPrice();
            }
        }
        mmap.put("procurementDeclare",sysProcurementdeclare);
        mmap.put("sumPrice",sumPrice);
        return prefix + "/view";
    }

    /**
     * 供应商短信发送
     * @param approveId
     * @param mmap
     * @return
     */
    @GetMapping("/duanxin/{approveId}")
    public String duanxin(@PathVariable("approveId")Long approveId, ModelMap mmap){
        SysApprove sysApprove = sysApproveService.selectSysApproveById(approveId);
        List<SysOfferinfo> offerinfos = sysOfferinfoService.selectByPlanId(sysApprove.getPurchasePlanId());
        List<SysOfferinfo> sysOfferinfoList = new ArrayList<SysOfferinfo>();
        for (int i = 0;i<offerinfos.size();i++){
            SysOfferinfo sysOfferinfo = new SysOfferinfo();
            sysOfferinfo.setBidInfoId(offerinfos.get(i).getBidInfoId());
            List<SysOfferinfo> sysOfferinfos = sysOfferinfoService.selectSysOfferinfoList(sysOfferinfo);
            for (SysOfferinfo offerinfo:sysOfferinfos ){
                SysSupplier sysSupplier = sysSupplierService.selectSysSupplierById(offerinfo.getSupplierId());
                offerinfo.setSysSupplier(sysSupplier);
                SysGoodparameter sysGoodparameter = sysGoodparameterService.selectSysGoodparameterById(offerinfo.getGoodParameterId());
                offerinfo.setSysGoodparameter(sysGoodparameter);
                sysOfferinfoList.add(offerinfo);
            }
        }
        mmap.put("list", sysOfferinfoList);
        mmap.put("procurementDeclareId",sysApprove.getProcurementDeclareId());
        return prefix + "/sendMessage";
    }

    @RequiresPermissions("system:approve:sendMessageToSupplier")
    @Log(title = "发送短信", businessType = BusinessType.INSERT)
    @PostMapping("/sendMessageToSupplier")
    @ResponseBody
    public AjaxResult sendMessageToSupplier(String supplierMobles,Long procurementDeclareId){
        String result = "", message = "";
        int success = 0;
        int error = 0;
        String[] mobles = supplierMobles.split(",");
        if(mobles.length > 0){
            SysProcurementdeclare procurementDeclare = sysProcurementdeclareService.selectSysProcurementdeclareById(procurementDeclareId);
            if(procurementDeclare!=null){
                for(int i = 0; i < mobles.length; i++){
                    String[] str = mobles[i].split("#");
                    String username = ruoYiConfig.getAccout();

                    String password = ruoYiConfig.getPassword();

                    String httpUrl = ruoYiConfig.getMsgUrl();
                    String content = "【兰州安宁财政局】"+ procurementDeclare.getUnitName()
                            + "采购"+str[1]+"的申报已审核通过，请尽快安排供货。联系人："
                            +procurementDeclare.getContactName()
                            +",手机号码："+procurementDeclare.getMobilePhone();
                    StringBuffer httpArg = new StringBuffer();
                    httpArg.append("u=").append(username).append("&");
                    httpArg.append("p=").append(Message.md5(password)).append("&");
//						httpArg.append("m=").append(mobles[i]).append("&");
                    httpArg.append("m=").append(str[0]).append("&");
                    httpArg.append("c=").append(Message.encodeUrlString(content, "UTF-8"));

                    result = Message.request(httpUrl, httpArg.toString());
                    if(result.equals("0")) {
                        success++;
                    }else{
                        error++;
                    }
                }
                message = success + "个供应商短信发送成功，" + error + "个供应商短信发送失败。";
                return AjaxResult.success(message);
            }else{
                return AjaxResult.error("系统错误：数据无法获取");
            }

        }else{
            return AjaxResult.error("没有可发送短信手机号码");
        }

    }




}
